package com.cardbaobao.cardbabyclient.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.LoanFilterActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SpeedLoanActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CreditCardIndexBusinessAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.LoanAuthTypeAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.expand.transformer.ScaleTransformer;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.BusinessClass;
import com.cardbaobao.cardbabyclient.model.HeadCommon;
import com.cardbaobao.cardbabyclient.model.LoanAuthTypeList;
import com.cardbaobao.cardbabyclient.model.result.HeadCommonResult;
import com.cardbaobao.cardbabyclient.model.result.LoanAuthTypeListResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.ViewUtil;
import com.cardbaobao.cardbabyclient.widget.RotateHeaderHandler;
import com.cardbaobao.cardbabyclient.widget.banner.ScalePagerView;
import com.cardbaobao.cardbabyclient.widget.banner.BannerHolderCreator;
import com.cardbaobao.cardbabyclient.widget.banner.BannerView;
import com.cardbaobao.cardbabyclient.widget.banner.BannerViewHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrUIHandler;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 11:06.
 * 贷款
 */

public class LoanFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }
    @BindView(R.id.ptr_view)
    PtrFrameLayout ptrLayout;

    @BindView(R.id.banner)
    BannerView<Banner.CarouselFigureListBean> bannerView;

    @BindView(R.id.nested_scroll_view)
    NestedScrollView scrollView;

    @BindView(R.id.recycler_view_top)
    RecyclerView recyclerViewTop;

//    @ViewInject(R.id.ll_marquee_container)
//    private LinearLayout llMarqueeContainer;
//
//    @ViewInject(R.id.marqueeView)
//    private MarqueeView marqueeView;

    @BindView(R.id.recycler_view_bottom)
    RecyclerView recyclerViewBottom;

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {
        ViewUtil.configBannerView(mApplicationContext, bannerView);

        mCurrentPageId= Self.Page.app_loan_index_page;

        initIntent();
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == 0) {
                    ptrLayout.setEnabled(true);
                } else {
                    ptrLayout.setEnabled(false);
                }
            }
        });
        final PtrUIHandler header = new RotateHeaderHandler(mContext);
        ptrLayout.setHeaderView((View) header);
        ptrLayout.addPtrUIHandler(header);
        ptrLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                bannerView.pause();
                loadHeaderData();//获取顶部轮播图数据
                loadAuthTypeData();//获取授权类型数据
            }
        });
        bannerView.setParent(ptrLayout);
        ptrLayout.disableWhenHorizontalMove(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrLayout.autoRefresh();
            }
        }, 200L);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 获取顶部公共数据
     */
    private void loadHeaderData() {
        Observable<String> observable= Api.getCommonHeader(Constant.ZCC0102);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                ptrLayout.refreshComplete();
            }

            @Override
            public void onError(Throwable e) {
                ptrLayout.refreshComplete();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                HeadCommonResult headCommonResult = JsonUtil.json2Object(s, HeadCommonResult.class);
                if (headCommonResult.getCode() == Constant.SUC_CODE) {
                    if (headCommonResult.getData() != null) {
                        //配置轮播图
                        if (headCommonResult.getData().getCarousel_figure_list() != null) {
                            setBannerUi(headCommonResult.getData().getCarousel_figure_list());
                        }
                        //配置业务分类
                        if (headCommonResult.getData().getTab_list() != null) {
                            setBusinessUi(headCommonResult.getData().getTab_list());
                        }
                        //配置跑马灯
//                        List<HeadCommon.MarqueeListBean> data=
//                                headCommonResult.getData().getMarquee_list();
//                        if(data!=null&&data.size()>0){
//                            setMarqueeUi(data);
//                        }
                    }
                } else {
                    ToastUtil.showToast(headCommonResult.getMsg());
                }
            }
        });
    }

    /**
     * 设置轮播图数据
     */
    private void setBannerUi(final List<Banner.CarouselFigureListBean> data) {
        bannerView.setPages(data, new BannerHolderCreator() {
            @Override
            public BannerViewHolder createViewHolder() {
                final ScalePagerView pagerView = new ScalePagerView();
                pagerView.setOnBannerItemClickedListener(new ScalePagerView.OnBannerItemClickedListener() {
                    @Override
                    public void onBannerItemClicked(Banner.CarouselFigureListBean bean) {
                        SelfUtils.buriedClickData(Self.Action.app_click_loan_index_top_banner,
                                Self.Action.app_click_loan_index_top_banner_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        CommonJumpController controller = new CommonJumpController(mContext);
                        Map<String, Object> extra = new HashMap<>();
                        extra.put(CommonJumpController.FROM_PAGE, "贷款首页-banner");
                        extra.put(EventWebViewActivity.WEB_TYPE_I, 31);
                        controller.bannerJump(bean, extra);
                    }
                });
                return pagerView;
            }
        }, new ScaleTransformer(0.8f));
        bannerView.start();
    }

    /**
     * 设置业务分类数据
     */
    private void setBusinessUi(final List<BusinessClass.TabListBean> data) {
        final GridLayoutManager manager =
                new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
        manager.setAutoMeasureEnabled(true);
        manager.setSmoothScrollbarEnabled(true);
        recyclerViewTop.setHasFixedSize(true);
        recyclerViewTop.setNestedScrollingEnabled(false);
        recyclerViewTop.setLayoutManager(manager);
        final CreditCardIndexBusinessAdapter adapter =
                new CreditCardIndexBusinessAdapter(mContext);
        adapter.setData(data);
        adapter.setClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                SelfUtils.buriedClickData(Self.Action.app_click_loan_index_crowd_item,
                        Self.Action.app_click_loan_index_crowd_item_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                BusinessClass.TabListBean bean = data.get(position);
                mIntent.setClass(mContext, LoanFilterActivity.class);
                //人群分类
                mIntent.putExtra(LoanFilterActivity.LOAN_FILTER_PROFESSION_S, bean.getCode());
                mIntent.putExtra(LoanFilterActivity.LOAN_FILTER_PROFESSION_NAME_S, bean.getName());
                mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);

            }
        });
        recyclerViewTop.setAdapter(adapter);
    }

    /**
     * 设置跑马灯数据
     */
    private void setMarqueeUi(final List<HeadCommon.MarqueeListBean> data) {
//        List<String> dataStr=new ArrayList<>();
//        for(int i=0,size=data.size();i<size;i++){
//            dataStr.add(data.get(i).getContent());
//        }
//        marqueeView.setFlipInterval(Constant.MARQUEE_INTERVAL_TIME);
//        marqueeView.startWithList(dataStr);
//        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, TextView textView) {
//                HeadCommon.MarqueeListBean bean=data.get(position);
//                CommonJumpController controller=new CommonJumpController(mContext);
//                Map<String,Object> extra=new HashMap<>();
//                extra.put(CommonJumpController.FROM_PAGE,"贷款首页-跑马灯");
//        extra.put(EventWebViewActivity.WEB_TYPE_I, 32);
//                controller.marqueeJump(bean,extra);
//            }
//        });
//        llMarqueeContainer.setVisibility(View.VISIBLE);
    }

    /**
     * 获取授权类型数据
     */
    private void loadAuthTypeData() {
        Observable<String> observable=Api.getLoanIndexAuthType();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                ptrLayout.refreshComplete();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                final LoanAuthTypeListResult listResult =
                        JsonUtil.json2Object(s, LoanAuthTypeListResult.class);
                if (listResult != null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            recyclerViewBottom.setHasFixedSize(true);
                            recyclerViewBottom.setNestedScrollingEnabled(false);
                            GridLayoutManager bottomManager =
                                    new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
                            bottomManager.setAutoMeasureEnabled(true);
                            bottomManager.setSmoothScrollbarEnabled(true);
                            recyclerViewBottom.setLayoutManager(bottomManager);
                            LoanAuthTypeAdapter bottomAdapter = new LoanAuthTypeAdapter(mContext);
                            bottomAdapter.setData(listResult.getData().getZizhi_list());
                            bottomAdapter.setClickedCallback(new RecycleItemClickedCallback() {
                                @Override
                                public void onRecycleItemClicked(int position) {
                                    SelfUtils.buriedClickData(Self.Action.app_click_loan_index_loan_qualifications_item,
                                            Self.Action.app_click_loan_index_loan_qualifications_item_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            prePageId);
                                    LoanAuthTypeList.LoanAuthType authType =
                                            listResult.getData().getZizhi_list().get(position);
                                    mIntent.setClass(mContext, SpeedLoanActivity.class);
                                    //贷款授权类型
                                    mIntent.putExtra(SpeedLoanActivity.CODE, authType.getCode());
                                    mIntent.putExtra(SpeedLoanActivity.TITLE_S, authType.getName());
                                    mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                                    startActivity(mIntent);
                                }
                            });
                            recyclerViewBottom.setAdapter(bottomAdapter);
                        }
                    }
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_index_loan;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
//            if(llMarqueeContainer.getVisibility()==View.VISIBLE){
//                marqueeView.stopFlipping();
//            }
            if(bannerView!=null){
                bannerView.pause();
            }
        } else {
//            if(llMarqueeContainer.getVisibility()==View.VISIBLE){
//                marqueeView.startFlipping();
//            }
            if(bannerView!=null){
                bannerView.start();
            }

            GoogleAnalyticsUtil.setScreenName(Google.NEW_LOAN);
        }
    }
}
